package logic

import (
	"bytes"
	"camera/C/Rpc/model/es"
	"context"
	"encoding/json"
	"log"

	"camera/C/Rpc/camera"
	"camera/C/Rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearEsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearEsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearEsLogic {
	return &SearEsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Es搜索
func (l *SearEsLogic) SearEs(in *camera.SearEsRequest) (*camera.ListResponse, error) {
	// todo: add your logic here and delete this line
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if in.FormWord != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodTitle": in.FormWord,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := es.Es.Search(
		es.Es.Search.WithContext(context.Background()),
		es.Es.Search.WithIndex("good"),
		es.Es.Search.WithBody(&buf),
		es.Es.Search.WithTrackTotalHits(true),
		es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	r := map[string]interface{}{}
	json.NewDecoder(res.Body).Decode(&r)
	var list []*camera.ListItem
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		good := hit.(map[string]interface{})["_source"].(map[string]interface{})

		list = append(list, &camera.ListItem{
			UserId:    int64(good["UserId"].(float64)),
			GoodTitle: good["GoodTitle"].(string),
			GoodStock: int64(good["GoodStock"].(float64)),
			GoodImage: good["GoodImage"].(string),
			GoodPrice: float32(good["GoodPrice"].(float64)),
			GoodLike:  int64(good["GoodLike"].(float64)),
			Id:        int64(good["ID"].(float64)),
		})
	}

	return &camera.ListResponse{
		List: list,
	}, nil
}
